package com.woyou.fragment.goods;

import java.util.ArrayList;
import java.util.List;

import com.jing.biandang.R;
import com.squareup.picasso.Picasso;
import com.woyou.activity.HomeActivity;
import com.woyou.bean.GoodsInfo;
import com.woyou.bean.OptionGroupInfo;
import com.woyou.bean.OptionInfo;
import com.woyou.bean.rpc.Result;
import com.woyou.bean.rpc.UpdateGoodsInfoReq;
import com.woyou.component.SuperUI;
import com.woyou.fragment.SuperFragment;
import com.woyou.model.rpc.ShopModel;
import com.woyou.utils.FormatTools;
import com.woyou.utils.LoginUtils;
import com.woyou.utils.ThreadPoolManager;
import com.woyou.utils.TypeJudgeTools;

import android.os.Bundle;
import android.text.Editable;
import android.text.Html;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class GoodsDetailsFragment extends SuperFragment implements OnClickListener, TextWatcher {
	private HomeActivity homeActivity;
	private View layout_goodsdetails;
	private ImageView layout_goodsdetails_iv;
	private EditText layout_goodsdetails_name;
	private TextView layout_goodsdetails_classify;
	private EditText layout_goodsdetails_price;
	private EditText layout_goodsdetails_unit;
	private LinearLayout layout_goodsdetails_attribute;
	// 操作面板
	private LinearLayout layout_goodsdetails_panel;
	private RelativeLayout layout_goodsdetails_cancel;
	private RelativeLayout layout_goodsdetails_submit;

	private GoodsInfo goodsInfo;
	
	UpdateGoodsInfoReq updateGoodsInfoReq;
	Result result = null;
	
	private List<OptionInfo> priceList = new ArrayList<OptionInfo>();

	/**
	 * 存放有属性的EditText
	 */
	private ArrayList<EditText> editTextList = new ArrayList<EditText>();

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		layout_goodsdetails = inflater.inflate(R.layout.layout_goodsdetails, container, false);
		homeActivity=(HomeActivity)getActivity();
		return layout_goodsdetails;
	}

	@Override
	public void onHiddenChanged(boolean hidden) {
		super.onHiddenChanged(hidden);
		if(!hidden){
			initData();
		}
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		initView();
		initData();
	}

	/**
	 * 初始化View
	 */
	public void initView() {
		layout_goodsdetails_iv = (ImageView) layout_goodsdetails.findViewById(R.id.layout_goodsdetails_iv);
		layout_goodsdetails_name = (EditText) layout_goodsdetails.findViewById(R.id.layout_goodsdetails_name);
		layout_goodsdetails_classify = (TextView) layout_goodsdetails.findViewById(R.id.layout_goodsdetails_classify);
		layout_goodsdetails_price = (EditText) layout_goodsdetails.findViewById(R.id.layout_goodsdetails_price);
		layout_goodsdetails_unit = (EditText) layout_goodsdetails.findViewById(R.id.layout_goodsdetails_unit);
		layout_goodsdetails_attribute = (LinearLayout) layout_goodsdetails
				.findViewById(R.id.layout_goodsdetails_attribute);
		layout_goodsdetails_panel = (LinearLayout) layout_goodsdetails.findViewById(R.id.layout_goodsdetails_panel);
		layout_goodsdetails_cancel = (RelativeLayout) layout_goodsdetails.findViewById(R.id.layout_goodsdetails_cancel);
		layout_goodsdetails_submit = (RelativeLayout) layout_goodsdetails.findViewById(R.id.layout_goodsdetails_submit);
		layout_goodsdetails_cancel.setOnClickListener(this);
		layout_goodsdetails_submit.setOnClickListener(this);

		// 监听EditText文本内容是否有改变，并且是否显示操作面板
		layout_goodsdetails_name.addTextChangedListener(this);
		layout_goodsdetails_price.addTextChangedListener(this);
		layout_goodsdetails_unit.addTextChangedListener(this);
	}

	/**
	 * 初始化数据
	 */
	public void initData() {

		if (layout_goodsdetails_unit != null) {
			// 清空editTextList
			editTextList.clear();

//			goodsInfo = (goodsInfo) aCache.getAsObject("goodsInfo");
			goodsInfo = (GoodsInfo) aCache.getAsObject("settingsGoods");
			if(!TypeJudgeTools.isNull(goodsInfo.getPrcUrl())){
				Picasso.with(homeActivity).load(goodsInfo.getPrcUrl()).into(layout_goodsdetails_iv);
			}
			layout_goodsdetails_name.setText("" + goodsInfo.getgName());
			layout_goodsdetails_classify.setText("分类：" + aCache.getAsString("categoryName"));
			layout_goodsdetails_price.setText("" + FormatTools.String2Money(String.valueOf(goodsInfo.getPrice())));
			layout_goodsdetails_unit.setText(Html.fromHtml(goodsInfo.getUnit()));
			
//			goodsInfo = mokc(goodsInfo);

			// 添加属性
			layout_goodsdetails_attribute.removeAllViews();
			if (goodsInfo.getOptionGroup() != null) {
				priceList.clear();
				//加载属性组
				for (int i = 0; i < goodsInfo.getOptionGroup().size(); i++) {
					View groupView = View.inflate(homeActivity,R.layout.item_optiongroupdetails, null);
					TextView groupName = (TextView) groupView.findViewById(R.id.item_optiongroup_name);
					groupName.setText("" + goodsInfo.getOptionGroup().get(i).getOptGName());
					layout_goodsdetails_attribute.addView(groupView);
					//加载属性
					for (int j = 0; j < goodsInfo.getOptionGroup().get(i).getOptList().size(); j++) {
						//加载可修改的属性
						if(goodsInfo.getOptionGroup().get(i).getIsChange()==1)
						{
							OptionInfo optionInfo = new OptionInfo();
							View childView = View.inflate(homeActivity,R.layout.item_goodsdetails, null);
							TextView name = (TextView) childView.findViewById(R.id.item_goodsdetails_name);
							EditText price = (EditText) childView.findViewById(R.id.item_goodsdetails_price);
							name.setText("" + goodsInfo.getOptionGroup().get(i).getOptList().get(j).getOptName());//属性名称
							price.setText("" + FormatTools.String2Money(String.valueOf(goodsInfo.getOptionGroup().get(i).getOptList().get(j).getPrice())));//属性价格
							
							optionInfo.setOptId(goodsInfo.getOptionGroup().get(i).getOptList().get(j).getOptId());
							optionInfo.setPrice(goodsInfo.getOptionGroup().get(i).getOptList().get(j).getPrice());
							priceList.add(optionInfo);
							layout_goodsdetails_attribute.addView(childView);

							// 将EditText对象存放到editTextList
							editTextList.add(price);
							// 监听EditText文本内容是否有改变，并且是否显示操作面板
							price.addTextChangedListener(this);
						}
						else
						{
							View childView = View.inflate(homeActivity,R.layout.item_goodsdetailstow, null);
							TextView name = (TextView) childView.findViewById(R.id.item_goodsdetails_name);
							TextView price = (TextView) childView.findViewById(R.id.item_goodsdetails_price);
							name.setText("" + goodsInfo.getOptionGroup().get(i).getOptList().get(j).getOptName());//属性名称
							price.setText("" + FormatTools.String2Money(String.valueOf(goodsInfo.getOptionGroup().get(i).getOptList().get(j).getPrice())));//属性价格
							layout_goodsdetails_attribute.addView(childView);
						}
					}
				}
			}
			layout_goodsdetails_panel.setVisibility(View.GONE);
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.layout_goodsdetails_cancel:
			initData();
			break;
		case R.id.layout_goodsdetails_submit:
			UpdateGoodsInfo();
			break;
		}

	}

	/**
	 * 判断该EditText 是否一个整数或者是正浮点数
	 * 
	 * @param et
	 * @return true是 false否
	 */
	public boolean isNumber(EditText et) {
		boolean isPN = TypeJudgeTools.isPositiveNumber(et.getText().toString());
		boolean isFPN = TypeJudgeTools.isFloatingPointNumber(et.getText().toString());
		String newStr = et.getText().toString().replaceAll("^(0+)", "");
		if (!isPN && !isFPN) {
			SuperUI.openToast(homeActivity, "数据格式不正确！");
			return false;
		}
		if(!et.getText().toString().equals("0"))
		{
			if(et.getText().toString().split("\\.").length>1)
			{
				if (et.getText().toString().split("\\.").length<2) {
					SuperUI.openToast(homeActivity, "数据格式不正确！");
					return false;
				}
			}
			else
			{
				if (newStr.length()!=et.getText().toString().length()) {
					SuperUI.openToast(homeActivity, "数据格式不正确！");
					return false;
				}
			}
		}
		return true;
	}

	/**
	 * 修改商品信息
	 */
	public void UpdateGoodsInfo() {
		updateGoodsInfoReq = new UpdateGoodsInfoReq();
		updateGoodsInfoReq.setsId(LoginUtils.getUserInfo(homeActivity).getsId());
		updateGoodsInfoReq.setPwd(LoginUtils.getUserInfo(homeActivity).getPwd());
		updateGoodsInfoReq.setgId(goodsInfo.getgId());
		updateGoodsInfoReq.setIsChange(1);
		if (!TypeJudgeTools.isNull(layout_goodsdetails_name.getText().toString())) {
			updateGoodsInfoReq.setgName(layout_goodsdetails_name.getText().toString());
		} else {
			SuperUI.openToast(homeActivity, "商品名称不能为空！");
			return;
		}
		if (!TypeJudgeTools.isNull(layout_goodsdetails_price.getText().toString())) {
			if (!isNumber(layout_goodsdetails_price)) {
				return;
			}
			updateGoodsInfoReq.setPrice(Float.valueOf(layout_goodsdetails_price.getText().toString()));
		} else {
			SuperUI.openToast(homeActivity, "商品价格不能为空！");
			return;
		}
		if (!TypeJudgeTools.isNull(layout_goodsdetails_unit.getText().toString())) {
			updateGoodsInfoReq.setUnit(layout_goodsdetails_unit.getText().toString());
		} else {
			SuperUI.openToast(homeActivity, "商品单位不能为空！");
			return;
		}
		// 重组resultStr  遍历属性是否改变
		List<OptionInfo> optionList = new ArrayList<OptionInfo>();
		if (goodsInfo.getOptionGroup() != null && priceList != null && editTextList.size() > 0) {
			for (int i = 0; i < priceList.size(); i++) {
				if (TypeJudgeTools.isNull(editTextList.get(i).getText().toString())) {
					SuperUI.openToast(homeActivity, "属性价格不能为空！");
					return;
				}
				if (!isNumber(editTextList.get(i))) {
					SuperUI.openToast(homeActivity, "属性价格格式不正确！");
					return;
				}
				if (!editTextList.get(i).getText().toString().equals(FormatTools.String2Money(String.valueOf(priceList.get(i).getPrice())))) {
					priceList.get(i).setPrice(Float.valueOf(editTextList.get(i).getText().toString()));
					optionList.add(priceList.get(i));
				}
			}
		}
		updateGoodsInfoReq.setPropList(optionList);
		ThreadPoolManager.getInstance().executeTask(new Runnable() {
			@Override
			public void run() {
				try {
					homeActivity.showLoadingHint();
					result = ShopModel.getInstance(homeActivity).updateGoodsInfo(updateGoodsInfoReq);
					if(result!=null && result.code==1)
					{
						homeActivity.runOnUiThread(new Runnable() {
							@Override
							public void run() {
								refreshData();
								SuperUI.openToast(homeActivity, result.msg);
								layout_goodsdetails_panel.setVisibility(View.GONE);
							}
						});
					} else if( result != null && result.code==-3 ) {
						homeActivity.homeController.exitLogin();
					} else {
						homeActivity.runOnUiThread(new Runnable() {
							@Override
							public void run() {
								initData();
								SuperUI.openToast(homeActivity, result.msg);
							}
						});
					}
				} catch (Exception e) {
					e.printStackTrace();
				} finally {
					homeActivity.hideLoadingHint();
				}
			}
		});
	}

	/**
	 * 判断是否要显示操作面板 true 显示 false 隐藏
	 */
	public boolean isShowControlPanel() {
		if (goodsInfo != null) {
			if (!layout_goodsdetails_name.getText().toString().equals(goodsInfo.getgName())) {
				return true;
			}
			if (!layout_goodsdetails_price.getText().toString().equals(FormatTools.String2Money(String.valueOf(goodsInfo.getPrice())))) {
				return true;
			}
			if (!layout_goodsdetails_unit.getText().toString().equals(goodsInfo.getUnit())) {
				return true;
			}
			// 遍历属性是否改变
			if (priceList != null) {
				if (editTextList.size() > 0) {
					for (int i = 0; i < priceList.size(); i++) {
						if (!editTextList.get(i).getText().toString()
								.equals(FormatTools.String2Money(String.valueOf(priceList.get(i).getPrice())))) {
							return true;
						}
					}
				}
			}
		}
		return false;
	}

	@Override
	public void beforeTextChanged(CharSequence s, int start, int count, int after) {
	}

	@Override
	public void onTextChanged(CharSequence s, int start, int before, int count) {
		// 判断内容是否有改变
		boolean isShow = isShowControlPanel();
		if (isShow) {
			layout_goodsdetails_panel.setVisibility(View.VISIBLE);
		} else {
			layout_goodsdetails_panel.setVisibility(View.GONE);
		}
	}

	@Override
	public void afterTextChanged(Editable s) {
	}
	
	public void refreshData()
	{
		if (goodsInfo.getOptionGroup() != null) {
			goodsInfo.setPrice(Float.valueOf(layout_goodsdetails_price.getText().toString()));
			goodsInfo.setUnit(layout_goodsdetails_unit.getText().toString());
			//加载属性组
			for (int i = 0; i < goodsInfo.getOptionGroup().size(); i++) {
				//加载属性
				for (int j = 0; j < goodsInfo.getOptionGroup().get(i).getOptList().size(); j++) {
					//加载可修改的属性
					if(goodsInfo.getOptionGroup().get(i).getIsChange()==1)
					{
						if (priceList.get(j).getOptId().equals(goodsInfo.getOptionGroup().get(i).getOptList().get(j).getOptId())) {
							goodsInfo.getOptionGroup().get(i).getOptList().get(j).setPrice(Float.valueOf(priceList.get(j).getPrice()));
						}
					}
				}
			}
			// 放置settingsGoods
			aCache.put("settingsGoods", goodsInfo);
		}
	}
	
	public GoodsInfo mokc(GoodsInfo gInfo)
	{
		List<OptionInfo> optList = null;
		List<OptionGroupInfo> groupList = new ArrayList<OptionGroupInfo>();
		String[] grouparray = {"奶茶", "红茶", "绿茶", "咖啡"};
		String[] optarray = {"冷", "热", "常温"};
		for (int j = 0; j < grouparray.length; j++) {
			OptionGroupInfo group = new OptionGroupInfo();
			group.setOptGId(String.valueOf(j));
			group.setOptGName(grouparray[j]);
			optList = new ArrayList<OptionInfo>();
			for (int i = 0; i < optarray.length; i++) {
				OptionInfo optionInfo = new OptionInfo();
				optionInfo.setOptId(String.valueOf(i));
				optionInfo.setOptName(optarray[i]);
				optionInfo.setPrice(i);
				optionInfo.setState(1);
				optList.add(optionInfo);
			}
			group.setOptList(optList);
			if(j==grouparray.length-1)
			{
				group.setIsChange(2);
			}
			else
			{
				group.setIsChange(1);
			}
			groupList.add(group);
		}
		gInfo.setOptionGroup(groupList);
		return gInfo;
	}
	
}
